package cn.loan.controller;

import cn.loan.config.key.RequestKey;
import cn.loan.config.key.SessionKey;
import cn.loan.config.key.StatusCode;
import cn.loan.entity.*;
import cn.loan.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.List;

/**
 * @Author: 毛苏宇
 * @Description: 贷款的一系列操作
 * @Date: Create in 13:47 2019/3/20
 */
@Controller
@RequestMapping("/loan")
public class LoanController {

    @Autowired
    private AuthenticationService authenticationService;
    @Autowired
    private QuotaService quotaService;
    @Autowired
    private CycleService cycleService;
    @Autowired
    private InterestRateService interestRateService;
    @Autowired
    private ByStagesService byStagesService;
    @Autowired
    private EducationService educationService;
    @Autowired
    private UserService userService;
    @Autowired
    private IdCardService idCardService;

    /**
     * 去认证页面
     *
     * @return 认证页面
     */
    @GetMapping("/auth")
    public String auth(HttpSession session, HttpServletRequest request) {
        User user = (User) session.getAttribute(SessionKey.SESSION_USER);
        int user_id = user.getUser_id();
        //查询是否存在身份证信息
        boolean idCardExist = idCardService.findIdCardExist(user);
        if (idCardExist) {
            //是否存在认证信息
            boolean flag = authenticationService.authIsExist(user_id);
            if (!flag) {
                List<Education> educations = educationService.getAll();
                request.setAttribute(RequestKey.REQUEST_EDUCATIONS, educations);
                //不存在则直接跳转至认证页面
                return "/Authentication";
            }
            //否则直接跳转至额度页面
            return "redirect:quota";
        } else {
            return "redirect:/card/idcard";
        }
    }


    /**
     * 查询认证信息是否存在
     *
     * @param session
     * @return
     */
    @PostMapping("/status.do")
    @ResponseBody
    public String doAuthStatus(HttpSession session) {
        User user = (User) session.getAttribute(SessionKey.SESSION_USER);
        int userId = user.getUser_id();
        //查询状态
        boolean exist = authenticationService.authIsExist(userId);
        if (exist) {
            return StatusCode.STATUS_EXIST;
        } else {
            return StatusCode.STATUS_NOT_EXIST;
        }
    }


    /**
     * 资料认证
     *
     * @param authentication 资料
     * @return 资料认证情况
     */
    @PostMapping("/auth.do")
    @ResponseBody
    public String doAuth(Authentication authentication, HttpSession session) {
        try {
            //查询数据库中是否有该邀请码
            boolean userCodeExist = userService.findCode(authentication.getUser_code());
            //存在则继续
            if (userCodeExist) {
                //得到用户
                User user = (User) session.getAttribute(SessionKey.SESSION_USER);
                //得到userId
                int userId = user.getUser_id();
                //查询状态,是否已经存在认证信息
                boolean exist = authenticationService.authIsExist(userId);
                if (!exist) {
                    //放入userId
                    authentication.setUser_id(userId);
                    //添加认证时间
                    authentication.setAuth_time(new Timestamp(System.currentTimeMillis()));
                    //查询该id是否存在,存在则返回不存在则为null
                    Education eduById = educationService.getEduById(authentication.getEducation_id());
                    //不存在则在数据库中查找最低学历
                    if (eduById == null) {
                        authentication.setEducation_id(educationService.getMinId());
                    }
                    //进行认证
                    boolean flag = authenticationService.addAuth(authentication);
                    if (flag) {
                        return StatusCode.STATUS_SUCCESS;
                    } else {
                        return StatusCode.STATUS_FAIL;
                    }
                } else {
                    return StatusCode.STATUS_EXIST;
                }
            } else {
                return StatusCode.STATUS_NOT_EXIST;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return StatusCode.STATUS_ERROR;
        }
    }


    /**
     * 去出额度页面
     *
     * @return 出额度页面
     */
    @GetMapping("/quota")
    public String quota(HttpServletRequest request, HttpSession session) {
        User user = (User) session.getAttribute(SessionKey.SESSION_USER);
        int userId = user.getUser_id();
        DecimalFormat decimalFormat = new DecimalFormat("###,###.00");
        //得到利率
        double interest_rate = interestRateService.findInterestRate();
        request.setAttribute(RequestKey.REQUEST_INTEREST_RATE, interest_rate);
        //如果邀请码正确
        if (authenticationService.getUserCodeExist(userId)) {
            //用户是否有额度
            boolean flag = quotaService.quotaIsExist(userId);
            if (flag) {
                //有额度则查询额度
                double quota = quotaService.getQuota(userId);
                //将额度格式化
                String money = decimalFormat.format(Math.floor(quota));
                //存储至request中
                request.setAttribute(RequestKey.REQUEST_QUOTA, money);
            } else {
                //3-9之间随机小数
                double ran = (Math.random() * 2) + 1;
                //保留小数点后一位
                String str = new DecimalFormat("#.0").format(ran);
                double k = Math.floor(Double.valueOf(str) * 10000);
                String money = decimalFormat.format(k);
                //额度对象
                Quota quota = new Quota(userId, Double.valueOf(k));
                //添加到数据库中
                boolean b = quotaService.addQuota(quota);
                request.setAttribute(RequestKey.REQUEST_QUOTA, money);
            }
        } else {
            return "redirect:/quota/no_quota";
        }
        return "/Quota";
    }


    /**
     * 额度是否存在
     *
     * @param session
     * @return
     */
    @PostMapping("/quotaExist")
    @ResponseBody
    public String quotaExist(HttpSession session) {
        //得到用户
        User user = (User) session.getAttribute(SessionKey.SESSION_USER);
        //得到用户id
        int userId = user.getUser_id();
        if (quotaService.quotaIsExist(userId)) {
            return StatusCode.STATUS_EXIST;
        } else {
            return StatusCode.STATUS_NOT_EXIST;
        }
    }


    @PostMapping("/available")
    @ResponseBody
    public String available(HttpSession session) {
        User user = (User) session.getAttribute(SessionKey.SESSION_USER);
        int userId = user.getUser_id();
        //总额度
        double quota = quotaService.getQuota(userId);
        //已用额度
        double balance = quotaService.getBalance(userId);
        //可用额度
        double available = quota - balance;
        if (available < 5000) {
            return StatusCode.STATUS_LIMIT;
        } else {
            return StatusCode.STATUS_NOT_LIMIT;
        }
    }


    /**
     * 去借款页面
     *
     * @return 借款页面
     */
    @GetMapping("/bystages")
    public String bystages(HttpServletRequest request, HttpSession session) {
        User user = (User) session.getAttribute(SessionKey.SESSION_USER);
        int userId = user.getUser_id();
        //是否有额度
        boolean quotaIsExist = quotaService.quotaIsExist(userId);
        if (quotaIsExist) {
            //拿到额度
            double quota = quotaService.getQuota(userId);
            //得到借款周期
            List<Cycle> allCycle = cycleService.getAllCycle();
            //得到银行卡信息,发卡机构和银行卡号
            Authentication bank = authenticationService.getBankNumOrName(userId);
            //得到利率
            double interest_rate = interestRateService.findInterestRate();
            //得到已用额度
            double balance = quotaService.getBalance(userId);
            //将已用额度存入request
            request.setAttribute(RequestKey.REQUEST_BALANCE, balance);
            request.setAttribute(RequestKey.REQUEST_INTEREST_RATE, interest_rate);
            request.setAttribute(RequestKey.REQUEST_BANK_INFO, bank);
            request.setAttribute(RequestKey.REQUEST_QUOTA, quota);
            request.setAttribute(RequestKey.REQUEST_ALL_CYCLE, allCycle);
            return "/bystages";
        } else {
            return "redirect:/home/index";
        }
    }


    /**
     * 得到全部借款周期
     *
     * @return 周期
     */
    @RequestMapping("/getCycle")
    @ResponseBody
    public List<Cycle> getCycle() {
        List<Cycle> allCycle = cycleService.getAllCycle();
        return allCycle;
    }


    /**
     * 借款
     *
     * @param byStages 借款信息
     * @param session
     * @return 借款状态
     */
    @PostMapping("/bystages.do")
    @ResponseBody
    public int doByStages(ByStages byStages, HttpSession session) throws Exception {
        final User user = (User) session.getAttribute(SessionKey.SESSION_USER);
        final int userId = user.getUser_id();
        //是否有额度
        final boolean quotaIsExist = quotaService.quotaIsExist(userId);
        if (quotaIsExist) {
            //是否有借款记录
            final boolean loanExist = byStagesService.getLoanExist(userId);
            if (!loanExist) {
                //得到额度
                final double quota = quotaService.getQuota(userId);
                //得到已借款的额度
                final double balance = quotaService.getBalance(userId);
                //如果总额度减去已借额度不足5000,则不予借款
                if ((quota - balance) < 5000) {
                    //余额不足,借款受限制
                    return StatusCode.STATUS_NUM_LIMIT;
                } else {
                    //得到利率
                    final double interest_rate = interestRateService.findInterestRate();
                    //得到总利息,总利息=贷款*利率*分期/100
                    final int fenqi = cycleService.getCycleNumber(byStages.getCycle_id());
                    //总利息
                    final double grossInterest = (byStages.getBs_loan() * interest_rate * fenqi) / 100;
                    //总利息
                    byStages.setBs_interest(grossInterest);
                    //用户id
                    byStages.setUser_id(userId);
                    //借款时间
                    byStages.setBs_time(new Timestamp(System.currentTimeMillis()));
                    //借款插入
                    boolean flag = byStagesService.addByStages(byStages);
                    if (flag) {
                        //插入成功
                        return StatusCode.STATUS_NUM_SUCCESS;
                    }
                    //借款失败
                    return StatusCode.STATUS_NUM_FAIL;
                }
            } else {
                //有借款记录
                return StatusCode.STATUS_NUM_EXIST;
            }
        } else {
            //没有额度
            return StatusCode.STATUS_NUM_NOT_EXIST;
        }
    }


}
